package com.base.saas.gateway.trace;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * @author 王清亮
 * @date 2025/8/2 22:21
 * @description TODO
 */
@Component
public class TraceGlobalFilter implements GlobalFilter, Ordered {
    private static final String ROOT_SPAN = "root";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取或生成 traceId
        String traceId = exchange.getRequest().getHeaders().getFirst(TraceContext.TRACE_ID);
        if (traceId == null) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }

        // 处理 parentSpanId
        String parentSpanId = exchange.getRequest().getHeaders().getFirst(TraceContext.SPAN_ID);
        if (parentSpanId == null) {
            // 如果是入口请求，标记为 root
            parentSpanId = ROOT_SPAN;
        }

        // 生成当前 spanId
        String spanId = TraceContext.generateSpanId();

        // 将追踪信息存入 Reactor Context
        String finalTraceId = traceId;
        String finalParentSpanId = parentSpanId;
        ServerHttpRequest mutatedRequest = exchange.getRequest().mutate()
                .header(TraceContext.TRACE_ID, traceId)
                .header(TraceContext.SPAN_ID, spanId)
                .header(TraceContext.PARENT_SPAN_ID, parentSpanId)
                .build();

        return chain.filter(exchange.mutate().request(mutatedRequest).build())
                .contextWrite(ctx -> ctx
                        .put("traceId", finalTraceId)
                        .put("spanId", spanId)
                        .put("parentSpanId", finalParentSpanId)
                );
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}